'use strict';
const db = uniCloud.database();
const collection = db.collection('comment');
const $ = db.command.aggregate
const fastscan = require('fastscan')
const uniID = require('uni-id')
exports.main = async (event, context) => {
	let params = event.params || {}
	let payload = {}
	let noCheckAction = ['getList', 'comment']
	if (noCheckAction.indexOf(event.action) === -1) {
		if (!event.uniIdToken) {
			return {
				code: 403,
				msg: '缺少token'
			}
		}
		payload = await uniID.checkToken(event.uniIdToken)
		if (payload.code && payload.code > 0) {
			return payload
		}
		params.uid = payload.uid
	}
	let res = {}
	switch (event.action) {
		case 'getList':
			payload = await uniID.checkToken(event.uniIdToken)
			if (payload.code == 0) {
				let total = (await collection.where({
					articleId: params.articleId
				}).count()).total
				
				let meComment = {}
				// 是否为自己评论
				if(params.getMe){
					meComment = await collection.where({
						userId: payload.uid,
						articleId: params.articleId
					}).field({
						'userId': false,
					}).get()
				}
				
				let pageSize = params.pageSize ? Number(params.pageSize) : 20
				let pageNumber = params.pageNumber ? Number((Number(params.pageNumber) - 1) * pageSize) : 0
				let list = await collection.aggregate()
					.match({
						articleId: params.articleId
					})
					.lookup({
						from: 'uni-id-users',
						localField: 'userId',
						foreignField: '_id',
						as: 'userInfo',
					}).replaceRoot({
						newRoot: $.mergeObjects([$.arrayElemAt(['$userInfo', 0]), '$$ROOT'])
					})
					.project({
						articleId: 1,
						comment_content: 1,
						comment_date: 1,
						nickname: 1,
						avatar: 1
					}).sort({
						comment_date: -1
					})
					.skip(pageNumber)
					.limit(pageSize)
					.end()

				res = {
					...list,
					meComment,
					total,
					code: 0,
					msg: '查询成功'
				}
			} else {
				res = payload
			}
			break; 
		case "comment":
			payload = await uniID.checkToken(event.uniIdToken)
				res = await collection.doc(payload.uid+params.articleId).set({
				  userId: payload.uid,
				  articleId: params.articleId,
				  comment_content: fastscan.filter(params.comment_content).text,
				  comment_date:Date.now()
				});
			res = {...res,code:0,msg:'评论成功'}
			break;
			
		default:
			res = {
				code: 403,
				msg: '非法访问54545'
			}
			break;
	}
	//返回数据给客户端
	return res
};
